﻿using System.Collections;
using System.Collections.Generic;

namespace Iot.TimingDatabase.Models;

/// <summary>
///     表示IoT数据库数据集的记录类型，实现了IReadOnlyList<IotDbData />接口
/// </summary>
/// <param name="Data">列数据的只读列表</param>
/// <param name="Timestamps">时间戳的只读列表</param>
public record IotDbDataSet(IReadOnlyList<IotDbColumnData> Data, IReadOnlyList<long> Timestamps)
    : IReadOnlyList<IotDbData>
{
    // 用于缓存数据的字典，避免重复计算
    private readonly Dictionary<int, IotDbData> _cache = [];

    /// <summary>
    ///     获取列数
    /// </summary>
    public int Column => Data.Count;

    /// <summary>
    ///     获取数据行数
    /// </summary>
    public int Count => Timestamps.Count;

    /// <summary>
    ///     实现IEnumerable<IotDbData />的GetEnumerator方法
    /// </summary>
    /// <returns>枚举器</returns>
    public IEnumerator<IotDbData> GetEnumerator()
    {
        for (var i = 0; i < Count; i++)
        {
            yield return this[i];
        }
    }

    /// <summary>
    ///     实现IEnumerable的GetEnumerator方法
    /// </summary>
    /// <returns>枚举器</returns>
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    /// <summary>
    ///     索引器，获取指定索引的数据行
    /// </summary>
    /// <param name="index">数据行的索引</param>
    /// <returns>对应索引的IotDbData对象</returns>
    public IotDbData this[int index]
    {
        get
        {
            // 首先检查缓存
            if (_cache.TryGetValue(index, out var value)) return value;
            // 检查索引是否有效
            if (Count <= index) return new IotDbData(0, []);
            // 创建新的数据行
            var data = new List<IotDbColumn>();
            for (var i = 0; i < Column; i++)
            {
                data.Add(new IotDbColumn(Data[i].Info, Data[i][index]));
            }

            // 将结果存入缓存
            return _cache[index] = new IotDbData(Timestamps[index], data);
        }
    }
}